package com.baidu.iit.pxp.behavior;

import com.baidu.iit.pvm.delegate.ActivityExecution;
import com.baidu.iit.pxp.BpmnError;
import com.baidu.iit.pxp.delegate.Expression;
import com.baidu.iit.pxp.util.ErrorPropagation;

/**
 * User: huangweili
 * Date: 14-4-30
 * Time: 下午5:35
 */
public class ServiceTaskExpressionActivityBehavior extends TaskActivityBehavior {

    protected Expression expression;
    protected String resultVariable;

    public ServiceTaskExpressionActivityBehavior(Expression expression, String resultVariable) {
        this.expression = expression;
        this.resultVariable = resultVariable;
    }

    public void execute(ActivityExecution execution) throws Exception {
        Object value = null;
        try {
            value = expression.getValue(execution);
            if (resultVariable != null) {
                execution.setVariable(resultVariable, value);
            }
            leave(execution);
        } catch (Exception exc) {

            Throwable cause = exc;
            BpmnError error = null;
            while (cause != null) {
                if (cause instanceof BpmnError) {
                    error = (BpmnError) cause;
                    break;
                }
                cause = cause.getCause();
            }

            if (error != null) {
                ErrorPropagation.propagateError(error, execution);
            } else {
                throw exc;
            }
        }
    }
}
